<template>
  <div class="paper">
    <el-card style="width:98%;margin:30px auto;">
      <div clas="title" style="font-weight:bold;font-size:17px">试卷管理</div>

      <div style="display: flex;justify-content: space-between">
        <div style="margin: 20px 2px">
          <el-button type="primary" icon="el-icon-plus" circle @click="open" title="添加"></el-button>
          <el-button type="danger" @click="deleteBatch" icon="el-icon-delete" title="批量删除" slot="reference"
                     style="margin-left: 10px"></el-button>
        </div>
        <div style="margin: 20px 5px">
          <el-input v-model="name" style="width: 200px" placeholder="请输入试卷名称"
                    suffix-icon="el-icon-search"></el-input>
          <el-button class="ml-5" type="primary" style="margin-left: 10px" @click="load">搜索</el-button>
          <el-button type="warning" @click="reset">重置</el-button>
        </div>


      </div>
      <el-table :data="tableData" border stripe :header-cell-class-name="headerBg"
                @selection-change="handleSelectionChange" size="medium"
      >

        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <!--     <el-table-column prop="id" label="ID" width="200">
             </el-table-column>-->
        <el-table-column prop="name" label="试卷名称">
        </el-table-column>

        <el-table-column
          prop="courseName"
          label="所属课程"
          align="center"
        >

          <template v-slot="scope">
            <!--<span v-if="courses && courses.length">{{courses.find(v=>v.id==scope.row.courseId).name}}</span>-->
            <div v-for="item in courses ">
              <span v-if="scope.row.courseId==item.id">{{ item.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="考试时长(分)">
        </el-table-column>
        <el-table-column prop="score" label="试卷总分">
        </el-table-column>

        <el-table-column prop="score" label="查看考卷">
          <template slot-scope="scope">
            <el-button type="primary" @click="viewPaper(scope.row.id)" icon="el-icon-edit">查看考卷</el-button>


          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" align="center">
          <template slot-scope="scope">
            <el-button type="primary" @click="takePaper(scope.row.id,scope.row.courseId)" icon="el-icon-edit">自动组卷
            </el-button>
            <el-button type="primary" plain @click="handlerPaper(scope.row.id,scope.row.courseId)" icon="el-icon-edit">
              手动组卷
            </el-button>
            <el-button type="primary" @click="edit(scope.row)" icon="el-icon-edit" circle></el-button>

            <!--删除-->
            <el-button @click="delete1(scope.row.id)"
                       slot="reference" type="danger" icon="el-icon-delete" circle
                       style="margin-left: 10px"></el-button>

          </template>
        </el-table-column>
      </el-table>
      <div style="padding: 10px 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      title="组卷"
      :visible.sync="dialogVisible1"
      :destroy-on-close="true"
    >
      <el-form :model="form1" label-width="120px" size="medium" ref="form1" class="demo-ruleForm">
        <el-form-item label="选择题数量" prop="name">
          <el-input v-model="form1.type1" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="判断题数量" prop="name">
          <el-input v-model="form1.type2" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简单题数量" prop="name">
          <el-input v-model="form1.type3" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1=false">取 消</el-button>
        <el-button type="primary" @click="generatePaper">确 定</el-button>
      </div>
    </el-dialog>

    <!--查看题目-->
    <el-dialog
      title="考卷"
      :visible.sync="dialogVisible2"
      :destroy-on-close="true">

      <el-card>
      <div style="margin:8px 5px;font-size: 14px">考试时长：{{totalTime}}分钟  &nbsp; &nbsp; &nbsp; 总分：{{paperSum}}分</div>
        <hr/>
        <div v-for="(item,index) in questions" :key="item.id" style="margin:18px 0">
          <div style="margin:15px 0;;font-size:20px"><span>{{ index + 1 }}.</span>{{ item.name }}
            <span style="font-size: 14px" v-if="item.type==1">(选择题 {{item.score}}分)</span>
            <span style="font-size: 14px" v-if="item.type==2">(判断题 {{item.score}}分)</span>
            <span style="font-size: 14px" v-if="item.type==3">(简答题 {{item.score}}分)</span>
          </div>
          <div v-if="item.type==1" style="margin:10px">
            <span style="margin-right: 20px">A.  {{ item.a }} </span>
            <span style="margin-right: 20px">B.  {{ item.b }} </span>
            <span style="margin-right: 20px">C.  {{ item.c }} </span>
            <span style="margin-right: 20px">D.  {{ item.d }} </span>
          </div>

          <div style="margin:10px">

            答案： {{ item.answer }}
          </div>
          <div style="margin:10px">

            解析： {{ item.detail }}
          </div>
        </div>
      </el-card>

    </el-dialog>

    <!--手动组卷-->

    <el-dialog
      title="手动组卷"
      :visible.sync="dialogVisible3"
      :destroy-on-close="true"
    >
      <el-form  label-width="120px" size="medium"  class="demo-ruleForm" style="margin-left: -55px" >

<!--        <el-form-item label="题目类型">
          <el-select v-model="type" placeholder="请选择试卷类型" @change="selectQuestion">
            <el-option label="选择题" value=1></el-option>
            <el-option label="判断题" value=2></el-option>
            <el-option label="简答题" value=3></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item  >
          <el-transfer v-model= "form3.handlerQuestionIds" :data="paperQuestions" filterable
                       :filter-method="filterMethod"
                       filter-placeholder="请输入类型：1选择. 2判断. 3简答"
                       :props="{key: 'id',label: 'name'}"
          ></el-transfer>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible3=false">取 消</el-button>
        <el-button type="primary" @click="generateHanderPaper">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="自动组卷"
      :visible.sync="dialogVisible"
      :destroy-on-close="true"
    >
      <el-form :model="form" label-width="120px" size="medium" :rules="rules" ref="form" class="demo-ruleForm">
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程">
            <el-option v-for="item in courses" :label="item.name" :value="item.id" :key="item.id"></el-option>

          </el-select>
        </el-form-item>
        <!--        <el-form-item label="试卷总分" prop="score">
                  <el-input v-model="form.score" autocomplete="off"></el-input>
                </el-form-item>-->
        <el-form-item label="考试时长(分)" prop="duration">
          <el-input v-model="form.duration" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>

    </el-dialog>


  </div>
</template>

<script>
import request from '../../utils/request'

export default {
  name: "Dict",
  data() {
    return {
      paperSum:0,
      rules: {
        name: [
          {required: true, message: '请输入考试名称', trigger: 'blur'},
          // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        score: [
          {required: true, message: '请输入试卷总分', trigger: 'blur'},
          // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],

        duration: [
          {required: true, message: '请选择考试时长', trigger: 'blur'},
          // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],

      },

      type: null,
      form2: {},
      form1: {},
      form3: {},
      questions: [],
      roles: [],
      headerBg: 'headerBg',
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 5,
      name: "",
      dialogVisible2: false,
      dialogVisible: false,
      dialogVisible1: false,
      dialogVisible3: false,
      form: {},
      courses: [],
      paperQuestions: [],
      //批量删除
      multipleSelection: [],
      paperQuestionsCopy:[],
      totalTime:0
    }
  },
  created() {
    //请求数据
    this.load()
    this.request.get("/course/findAll").then(res => {
      this.courses = res.data
    })

  },
  methods: {

    filterMethod(query, item) {
      return !query || query==item.type;
    },
/*
    selectQuestion(){
      console.log(this.paperQuestions)
      this.paperQuestions=this.paperQuestionsCopy.filter(v=>v.type==this.type)
    },*/

    generateHanderPaper() {
      this.request.post("/paper/handPaper", this.form3).then(res => {
        if (res.code == 200) {
          this.dialogVisible3 = false
          this.$message({
            type: 'success',
            message: '组卷成功!'
          });
          this.load()
        } else {
          this.$message({
            type: 'error',
            message: '组卷失败!'
          });
        }
      })
    },

    //手动组卷
    handlerPaper(paperId, courseId) {
      this.dialogVisible3 = true;
      this.request.get("/question/findList").then(res => {
        this.paperQuestions = res.data.filter(v => v.courseId === courseId);
        //备份原始数据
        // this.paperQuestionsCopy=JSON.parse(JSON.stringify(this.paperQuestions))
      })
      this.form3 = {handlerQuestionIds:[], paperId:paperId}
      // this.handlerQuestionIds = []
      this.type=null

    },
    //查看考卷
    viewPaper(paperId) {

      request.get("/paper/viewPaper/" + paperId).then(res => {
        this.dialogVisible2 = true
        this.questions = res.data

        var sum=0;
        this.questions.forEach(item=>{
         sum=parseInt(item.score)+sum;
        })
        this.paperSum=sum;

      })


      this.request.get("/paper/findById/"+paperId).then(res => {
        this.totalTime=res.data.duration;
      })

    },
    //生成试卷
    generatePaper() {
      request.post("/paper/takePaper", this.form1).then(res => {
        if (res.code == 200) {
          this.dialogVisible1 = false
          this.$message({
            type: 'success',
            message: '组卷成功!'
          });




        } else {
          this.$message({
            type: 'error',
            message: '组卷失败!'
          });
        }
      })

    },
    takePaper(paperId, courseId) {
      this.form1 = {type1: 4, type2: 4, type3: 2, paperId: paperId, courseId: courseId}
      this.dialogVisible1 = true
    },

    //消除校验
    resetForm() {
      this.$nextTick(() => {

        this.$refs.form.resetFields();
      })

      this.dialogVisible = false

    },
    deleteBatch() {
      let ids = this.multipleSelection.map(v => v.id)  //将对象数变为纯id数组
      this.$confirm('确定批量删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'msgbox',
        type: 'warning'
      }).then(() => {
        request.post("/paper/del/batch", ids).then(res => {
          if (ids.length === 0) {
            this.$message({
              type: 'warning',
              message: '请选择数据!'
            });
            return
          }
          if (res) {
            this.$message({
              type: 'success',
              message: '批量删除成功!'
            });
            this.load()
          } else {
            this.$message({
              type: 'error',
              message: '批量删除失败!'
            });
          }

        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //批量删除
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    //删除
    delete1(id) {
      this.$confirm('确定删除此考卷, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'msgbox',
        type: 'warning'
      }).then(() => {
        request.delete("/paper/delete/" + id).then(res => {
          if (res) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.load()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }

        })

      }).catch(() => {
        this.$message({
          type: 'success',
          message: '已取消删除'
        });
      });
    },

    //更新
    edit(row) {
      this.form = row
      this.dialogVisible = true
    },

    //新增
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {  // 表单校验合法


          request.post("/paper/save", this.form).then(res => {
            if (res) {
              this.$message({
                type: "success",
                message: "保存成功"

              })
              this.dialogVisible = false
              // sessionStorage.setItem("user", JSON.stringify(this.form))
              this.load()
            } else {
              this.$message({
                type: "error",
                message: "保存失败"
              })
            }
          })
        }
      })
    },
    //新增弹窗
    open() {
      this.dialogVisible = true
      this.form = {}
    },
    //重置
    reset() {
      this.name = "",
        this.load()
    },

    //分页
    load() {
      request.get("/paper/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,

        }
      }).then(res => {

        this.tableData = res.data.records
        this.total = res.data.total
      })


      /* fetch("http://localhost:9091/user/page?pageNum="+this.pageNum+"&pageSize="+this.pageSize+"&username="+this.username+"&nickname="+this.nickname).then(res => res.json()).then(res => {
           console.log(res)
           this.tableData = res.data
           this.total = res.total
       })*/
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.load()

    },
    handleCurrentChange(val) {
      this.pageNum = val

      this.load()
    }
  }
}
</script>

<style lang="scss" scope>

.paper{
  .headerBg {
    background: #eee !important;
  }

  .el-dialog {
    width: 50%;
  }


  @media screen and (max-width: 440px) {
    .el-dialog {
      width: 90%;
    }

    @media only screen and (min-width:600px) and (max-width:1200px){
      .el-dialog {
        width: 60%;
      }
    }

    @media only screen and (min-width:441px) and (max-width:599px){
      .el-dialog {
        width: 80%;
      }
    }
  }
}


</style>

<style >

@media (max-width: 720px) {
  .msgbox{
    width: 327px !important;
  }
}

</style>
